package com.bosssoft.user.permission.center.serve.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import com.bosssoft.user.permission.center.serve.dao.entity.TreeNode;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.bosssoft.user.permission.center.serve.dao.entity.Role;
import com.bosssoft.user.permission.center.serve.dao.entity.UserRoleInfo;
import com.bosssoft.user.permission.center.serve.dao.mapper.UserEntityMapper;
import com.bosssoft.user.permission.center.serve.pojo.query.UserEntity;
import com.bosssoft.user.permission.center.serve.pojo.vo.UserVo;
import com.bosssoft.user.permission.center.serve.service.UserService;
import com.bosssoft.user.permission.center.serve.util.LoginTokenUtil;
import com.bosssoft.user.permission.center.serve.util.UserTypeUtil;
import common.data.commonresponse.CommonPage;
import common.util.IdGeneratorUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserEntityMapper userEntityMapper;
    @Autowired
    private IdGeneratorUtil idGeneratorUtil;
    public CommonPage<UserEntity> queryUserList(UserEntity userEntity, Integer page, Integer limit) {
        List<UserEntity> result = userEntityMapper.queryUserList(userEntity);
        int pages;
        /**
         * 构建包含分页信息的列表
         */
        if(result.size()%limit==0){
            pages = result.size()/limit;
        }else{
            pages = result.size()/limit+1;
        }
        return new CommonPage((long) result.size(),page,limit,pages,result);
    }

    public CommonPage<UserRoleInfo> selectRoleList() {
        List<Role> tempResult = userEntityMapper.selectRoleList();
        List<UserRoleInfo> result = new ArrayList<>();
        for(int i = 0;i<tempResult.size();i++){
            UserRoleInfo userRoleInfo = new UserRoleInfo();
            userRoleInfo.setCode(tempResult.get(i).getCode());
            userRoleInfo.setName(tempResult.get(i).getName());
            userRoleInfo.setId(String.valueOf(tempResult.get(i).getId()));
            result.add(userRoleInfo);
        }
        int pages;
        int limit = 1;
        int page = 1;
        /**
         * 构建包含分页信息的列表
         */
        if(result.size()%limit==0){
            pages = result.size()/limit;
        }else{
            pages = result.size()/limit+1;
        }
        return new CommonPage((long) result.size(),page,limit,pages,result);
    }

    public CommonPage<UserVo> selectUserInfo(UserEntity userEntity, Integer page, Integer limit) {
        if(userEntity.getUserId()==null||userEntity.getUserId().equals("")||userEntity.getUserId().length()==0){
            userEntity.setUserId("");
        }
        if(userEntity.getUsername()==null||userEntity.getUsername().equals("")||userEntity.getUsername().length()==0){
            userEntity.setUsername("");
        }
        List<Long> userCharacterList = new ArrayList<>();
        boolean bool = true;
        if(userEntity.getUserCharacter()==null||userEntity.getUserCharacter().equals("")||userEntity.getUserCharacter().length()==0){
            userEntity.setUserCharacter("");
            bool = false;
        }else{
            userCharacterList = userEntityMapper.selectUserRoleByName(userEntity.getUserCharacter());
            if(userCharacterList.size()==0){
                userCharacterList.add(467L);
            }
        }

        if(userEntity.getTelephone()==null||userEntity.getTelephone().equals("")||userEntity.getTelephone().length()==0){
            userEntity.setTelephone("");
        }

        HashMap<String,Object> userRoleInfo = new HashMap<>();
        userRoleInfo.put("userId",userEntity.getUserId());
        userRoleInfo.put("username",userEntity.getUsername());
        userRoleInfo.put("telephone",userEntity.getTelephone());
        System.out.println(userCharacterList);
        userRoleInfo.put("userCharacterList",userCharacterList);
        List<UserEntity> result = new ArrayList<>();
        //查询用户信息
        if(bool){
            result = userEntityMapper.selectUserInfo(userRoleInfo);
        }else{
            result = userEntityMapper.selectUserInfo1(userEntity);
        }
        List<UserVo> resultEnd = new ArrayList<>();
        for(int i = 0;i< result.size();i++){
            UserVo userVo = UserTypeUtil.userTypeUtil1(result.get(i));
            userVo.setRoleList(UserTypeUtil.userTypeUtil2(userEntityMapper.selectUserRole(result.get(i).getId().toString())));
            userVo.setDepartmentList(userEntityMapper.selectUserDepartment());
            userVo.setPositionList(userEntityMapper.selectUserPosition());
            resultEnd.add(userVo);
        }
        int pages;
        /**
         * 构建包含分页信息的列表
         */
        if(result.size()%limit==0){
            pages = result.size()/limit;
        }else{
            pages = result.size()/limit+1;
        }
        return new CommonPage((long) result.size(),page,limit,pages,resultEnd);
    }

    public boolean addUserInfo(UserEntity userEntity){
        userEntity.setId(idGeneratorUtil.snowflakeId());
        userEntityMapper.insertBasicUser(UserTypeUtil.userTypeUtil3(userEntity));
        int userResult = userEntityMapper.insert(userEntity);
        return userResult>0;
    }

    public boolean modifyUserInfo(UserEntity userEntity){
        userEntityMapper.updateBasicUser(UserTypeUtil.userTypeUtil3(userEntity));
        int userResult = userEntityMapper.updateByUserId(userEntity);
        return userResult>0;
    }

    public boolean modifyUserStatus(UserEntity userEntity){
        HashMap<String,Object> map = new HashMap<>();
        map.put("status",UserTypeUtil.userStatusUtil(userEntity.getUserStatus()).toString());
        map.put("id",userEntity.getId());
        userEntityMapper.updateBasicUserStatus(map);
        int userResult = userEntityMapper.updateStatus(userEntity);
        return userResult>0;
    }

    public boolean deleteUsersByIds(List<String> ids){
        userEntityMapper.deleteBasicUsers(ids);
        int result = userEntityMapper.deleteUsersByIds(ids);
        return result>0;
    }

    public boolean startUsers(List<String> ids){
        UserEntity userEntity = new UserEntity();
        userEntity.setUserStatus("published");
        for(int i = 0;i< ids.size();i++){
            userEntity.setId(Long.valueOf(ids.get(i)));
            modifyUserStatus(userEntity);
        }
        return true;
    }

    public boolean shutUsers(List<String> ids){
        UserEntity userEntity = new UserEntity();
        userEntity.setUserStatus("draft");
        for(int i = 0;i< ids.size();i++){
            userEntity.setId(Long.valueOf(ids.get(i)));
            modifyUserStatus(userEntity);
        }
        return true;
    }

    public boolean deleteUserById(UserEntity userEntity){
        userEntityMapper.deleteBasicUser(userEntity.getId().toString());
        int userResult = userEntityMapper.deleteUserById(userEntity);
        return userResult>0;
    }

    @Override
    public boolean addUserRoleInfo(List<String> userIds, List<String> roleIds) {
        int result = 0;
        HashMap<String,Object> allocateInfo = new HashMap<>();
        for(int i = 0;i<userIds.size();i++){
            allocateInfo.put("user_id",userIds.get(i));
            userEntityMapper.deleteUserRole(allocateInfo);
            for(int j = 0;j<roleIds.size();j++){
                allocateInfo.put("id",String.valueOf(idGeneratorUtil.snowflakeId()));
                allocateInfo.put("role_id",roleIds.get(j));
                result += userEntityMapper.insertUserRole(allocateInfo);
            }
        }
        return result==userIds.size()*roleIds.size();
    }

    public List<Tree<String>> getTree() {
        List<TreeNode> list = new ArrayList<>();
        List<TreeNode> listd = userEntityMapper.selectDepartmentTree();
        for(int i =0;i<listd.size();i++){
            listd.get(i).setParentId(111L);
            list.add(listd.get(i));
        }
        List<TreeNode> listp = userEntityMapper.selectPositionTree();
        for(int i =0;i<listp.size();i++){
            listp.get(i).setParentId(222L);
            list.add(listp.get(i));
        }
        List<TreeNode> listr = userEntityMapper.selectRoleTree();
        for(int i =0;i<listr.size();i++){
            listr.get(i).setParentId(333L);
            list.add(listr.get(i));
        }
        TreeNode treeNode1 = new TreeNode();
        treeNode1.setId(111L);
        treeNode1.setName("部门");
        treeNode1.setParentId(-1L);
        TreeNode treeNode2 = new TreeNode();
        treeNode2.setId(222L);
        treeNode2.setName("职位");
        treeNode2.setParentId(-1L);
        TreeNode treeNode3 = new TreeNode();
        treeNode3.setId(333L);
        treeNode3.setName("角色");
        treeNode3.setParentId(-1L);
        list.add(treeNode1);
        list.add(treeNode2);
        list.add(treeNode3);
        List<TreeNode> list2 = CollUtil.newArrayList();
        //浅拷贝赋值
        list2.addAll(list);

        // rootId
        String pid = "-1";
        //配置
        TreeNodeConfig nodeConfig = new TreeNodeConfig();
        // 自定义属性名 都要默认值的
        //设置ID对应的名称
        nodeConfig.setIdKey("id");
        // 最大递归深度 3级目录
        nodeConfig.setDeep(2);
        System.out.println(list2);
//        入参
//        tree:  最终要返回的数据
//        node:  lists数据
//        返回
//        Tree<String>
//        Tree: 转换的实体 为数据源里的对象类型
//        String: ID类型
        //转换器
        List<Tree<String>> treeList = TreeUtil.build(list2, pid, nodeConfig,
                (node, tree) -> {
                    //id
                    tree.setId(String.valueOf(node.getId()));
                    //姓名
                    tree.setName(node.getName());
                    //获取父节点id
                    tree.setParentId(String.valueOf(node.getParentId()));
                });
        log.info(treeList.toString());
        System.out.println("rrr");
        return treeList;

    }
}

